﻿using System;
using System.Diagnostics;
using System.IO;

namespace Utity
{
    public class RAR_ZIP_UNZIP_Class
    {
        public void Zip(string sourceFolder, string targetFullName, string pwd)
        {
            string rarProgram = FindrarProgram();
            string zipType = Path.GetExtension(targetFullName).ToLower().TrimStart('.');

            if (File.Exists(targetFullName))
            {
                File.Delete(targetFullName);
            }

            ProcessStartInfo startinfo = null;
            if (!string.IsNullOrEmpty(pwd))
            {
                startinfo = new ProcessStartInfo(rarProgram, string.Format("A -r -p{2} -ep1 {0} {1}  -INUL -IBCK ", targetFullName, sourceFolder, pwd));
            }
            else
            {
                startinfo = new ProcessStartInfo(rarProgram, string.Format("A -r -ep1 {0} {1}  -INUL -IBCK ", targetFullName, sourceFolder));
            }
            startinfo.FileName = rarProgram;
            startinfo.ErrorDialog = false;
            startinfo.UseShellExecute = false;
            startinfo.WindowStyle = ProcessWindowStyle.Hidden;
            Process p = Process.Start(startinfo);
            p.WaitForExit();
            int i = p.ExitCode;
            if (i != 0)
                throw new Exception("压缩失败!");
        }

        private string FindrarProgram()
        {
            //RegistryKey the_Reg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\shell\ope n\command");
            //object the_Obj = the_Reg.GetValue("");
            //if (the_Obj == null)
            //{
            //    throw new ArgumentNullException("没有安装WinRAR软件");
            //}
            //string rarProgram = the_Obj.ToString();
            //the_Reg.Close();
            //return rarProgram.Substring(1, rarProgram.Length - 7);
            // return Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "RARLib", "WinRAR.exe");
            return System.Configuration.ConfigurationManager.AppSettings["WinRAR_Path"];
        }
    }
}